<!-- 通报modal -->
<template>
  <a-modal :bodyStyle="{ padding: '0', 'max-height': '80vh', 'overflow-y': 'auto' }" :title="title" :width="1000" :maskClosable="false" :visible="visible" @cancel="visible = false" :button_loading="button_loading">
    <a slot="footer">
      <a-button @click="visible = false">{{ cancelText }}</a-button>
      <a-button v-if="actionType != 'view'" type="primary" @click="handleSubmit">{{ okText }}</a-button>
    </a>
    <a-spin :indicator="indicator" :spinning="spinning" :tip="tip">
      <div class="spin-content">
        <a-form :form="form" :class="{ disable: actionType == 'view' ? true : false }">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="标题">
                <a-input placeholder="填写标题" v-decorator="[
                    'title',
                    { rules: [{ required: true, message: '请填写标题!' }] },
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="通知时间">
                <a-date-picker :show-time="{ format: 'HH:mm' }" format="YYYY-MM-DD HH:mm" v-decorator="[
                    'notificationTime',
                    {
                      rules: [{ required: true, message: '请选择活动时间!' }],
                    },
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="附件">
                <a-upload :action="a" :headers="headers" accept=".docx,.doct,.doc,.pdf" :file-list="fileList" @change="handleChange" :beforeUpload="beforeUpload">
                  <div>
                    <a-button> <a-icon type="upload" /> 上传 </a-button>
                  </div>
                </a-upload>
              </a-form-item>
            </a-col>

            <a-col class="gutter-row" :span="24">
              <a-form-item v-bind="formItemLayout1" label="通知内容">
                <a-textarea placeholder="通知内容" :rows="4" v-decorator="['context']" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-spin>
  </a-modal>
</template>

<script>
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { getImg } from '@/api/students'

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {
    actionType: {
      type: String,
      required: false,
      default: "add",
    },
  },
  data () {
    //这里存放数据
    return {
      a: null,
      headers: {
        authorization: "authorization-text",
      },
      action: "add",
      headers: {},
      currentId: null,
      CodeDisabled: false,
      required: false,
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      form: this.$form.createForm(this),
      button_loading: false,
      spinning: false,
      tip: null,
      title: "查看",
      visible: false,
      Photoloading: false,
      okText: "保存",
      cancelText: "取消",
      notificationTypeList: [],
      supervisionList: [],
      fileList: [],
      PhotoUrlDb: {},
      PhotoUrl: '',
      PhotoUrlDbString: '',
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      formItemLayout1: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created () { },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted () { },
  //方法集合
  methods: {
    view (data) {
      if (data) {
        Object.assign(this, {
          spinning: true,
          visible: true,
          CodeDisabled: false,
          currentId: data.id,
        });
        this.initData(data);
      } else {
        this.visible = true;
        this.form.resetFields();
        this.currentId = null;
        this.fileList = [];
      }
      switch (this.actionType) {
        case "add":
          this.okText = '保存'
          this.title = "添加工作通知";
          break;
        case "edit":
          this.okText = '保存'
          this.title = "编辑工作通知";
          break;
        case "view":
          this.title = "查看工作通知";
          break;
      }
    },
    handlePreview (file) {
      this.$refs.photomodal.view(file);
    },

    closeModal () {
      this.form.resetFields();
      this.visible = false;
    },

    initData (data) {
      this.fileList = []
      setTimeout(() => {
        this.spinning = false;
        this.form.setFieldsValue({
          ...data,
          notificationTime: this.$moment(data.notificationTime),
        });
        this.PhotoUrlDb = data.Annexs

        if (data.Annexs && data.Annexs.length > 0) {
          data.Annexs.forEach(item => {
            const a = {
              uid: String(item.ID),
              name: String(item.OldFileName),
              status: 'done',
              url: getImg(`${item.Path}/${item.NewFileName}`)
            }
            this.fileList.push(a)
          })
        } else {
          this.fileList = []
        }

        console.log(this.fileList)
      }, 500);
    },

    handleSubmit () {
      let _this = this;
      _this.form.validateFields((err, values) => {
        if (!err) {
          let Uploads = []
          this.fileList.map(aa => {
            if (aa.scan) {
              aa.response && Uploads.push(aa.response)
            }
            if (!aa.url && !aa.scan) {
              aa.response && Uploads.push(aa.response)
            }
            if (aa.url && !aa.scan) {
              Uploads.push(_this.PhotoUrlDb.find(a => a.ID == aa.uid))
            }

          })
          let params = {
            ...values,
            id: _this.currentId,
            Annexs: Uploads,
            notificationTime: _this
              .$moment(values.notificationTime)
              .format("YYYY-MM-DD"),
          };
          _this.$emit("save", { ...params });
        }
      });
    },

    handleChange ({ file, fileList }) {
      console.log(222222, fileList)
      this.fileList = fileList;
      if (file.status === 'error') {
        this.$message.error(`认证过期:${file.response}`)
      }
      if (file.status === 'uploading') {
        this.Photoloading = true
        return
      }
      if (file.status === 'done') {
        this.PhotoUrlDb = file.response

        // this.PhotoUrlDbString = `${this.PhotoUrlDb.Path}/${this.PhotoUrlDb.NewFileName}`
        this.Photoloading = false
      }

      // console.log(11122222,fileList)
    },

    beforeUpload (file) {
      const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token;
      this.headers = {
        authorization: "Bearer " + token,
      };
      this.a =
        process.env.VUE_APP_API_BASE_URL +
        `/api/Upload/UploadAnnex?tablename=WorkNotice&signname=Annexs`;
      let fileType = file.name.replace(/.+\./, "")
      const isJpgOrPng = fileType === 'doc' || fileType === 'docx' || fileType === 'pdf'

      if (!isJpgOrPng) {
        this.$message.error('您只能上传doc,docx,pdf文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("必须小于10MB!");
      }
      return isLt2M;
    },
  },
};
</script>
<style lang="less">
//@import url(); 引入公共css类
.spin-content {
  padding: 20px;
}

.disable {
  pointer-events: none;
}
</style>
